const express = require('express')
const router = express.Router()
const result = require('../utils/response')
const dbConfig = require('../config/database')
const fs = require('fs')
const path = require('path')
const mysql = require('mysql');

router.post('/detail', (req, res) => {
  res.send(result.success(dbConfig))
})

router.post('/save', async (req, res) => {
  const data = req.body
  const host = data.host
  const user = data.user
  const password = data.password
  const port = data.port
  const database = data.database
  // 修改jar包配置文件
  let cif = fs.readFileSync(path.join(__dirname, '../lib/application.properties'), 'utf8')
  cif = cif.replace(new RegExp(`${dbConfig.host}:${dbConfig.port}/${dbConfig.database}`, 'g'), `${host}:${port}/${database}`)
  cif = cif.replace(new RegExp(`username=${dbConfig.user}`, 'g'), `username=${user}`)
  cif = cif.replace(new RegExp(`password=${dbConfig.password}`, 'g'), `password=${password}`)
  fs.writeFileSync(path.join(__dirname, '../lib/application.properties'), cif, 'utf8')
  // 修改本地配置文件
  const log = fs.writeFileSync(path.join(__dirname, '../config/database.js'), `module.exports = ${JSON.stringify(data)}`)
  // 数据库插入数据

  // 创建数据库
  const createDb = () => {
    return new Promise((resolve, reject) => {
      data.database = 'mysql';
      execSql(`CREATE DATABASE IF NOT EXISTS ${database} DEFAULT CHARSET utf8 COLLATE utf8_general_ci;`, data, back => resolve(back))
    })
  }
  await createDb()
  data.database = database;

  // 创建数据库表
  const createTb = () => {
    return new Promise((resolve, reject) => {
      const sql = fs.readFileSync(path.join(__dirname, '../lib/auto_code_cloud.sql'), 'utf8')
      //sql数据进行处理
      const lines = sql.split('\n')
      let sqlStr = '';

      for (let line of lines) {

        if (line.startsWith('LOCK') || line.startsWith('#') || line.startsWith('DROP')) {
          continue
        }

        if (line.startsWith('/*!')) {
          line = line.substring(line.indexOf(' '), line.lastIndexOf(' ')) + ';'
        }

        if (line.startsWith('CREATE TABLE')) {
          line = line.replace('CREATE TABLE','CREATE TABLE IF NOT EXISTS')
        }

        sqlStr += line;
      }
      execSql(`${sqlStr}`, data, back => resolve(back))
    })
  }

  await createTb()
  res.send(result.success())
})

const execSql = (sql,cif,callback) =>{
  cif.multipleStatements = true;
  cif.useConnectionPooling = true;
  const connection = mysql.createConnection(cif);
  connection.connect(function(err){
    if(err){
      console.log('数据库链接失败');
      //throw err;
    }
    connection.query( sql, [], function(err,results,fields ){
      if(err){
        console.log('数据操作失败');
        //throw err;
      }
      callback && callback(JSON.parse(JSON.stringify(results || null)));
      connection.end(function(err){
        if(err){
          console.log('关闭数据库连接失败！');
          //throw err;
        }
      });
    });
  });
}

module.exports = router
